<template>
  <div class="comp-detail-page-header">
    <div class="flex items-center">
      <n-button @click.stop="handleClickBack">
        <template #icon>
          <n-icon><arrow-back /></n-icon>
        </template>
      </n-button>
      <span class="page-title">{{ props.title }}</span>
    </div>
    <slot></slot>
  </div>
</template>
<script setup lang="ts">
import { ArrowBack } from "@vicons/ionicons5";
import { onMounted, onUnmounted, ref } from "vue";
import { useRouter } from "vue-router";
import type { IPageHeaderProps } from "./props";

const router = useRouter();
const emits = defineEmits(["back"]);

const props = withDefaults(defineProps<IPageHeaderProps>(), {
  title: "",
  preventBack: false,
  confirmMessage: "您确定要离开当前页面吗？未保存的数据将会丢失。"
});

// 是否已经添加了beforeunload事件监听器
const hasAddedListener = ref(false);

// 处理beforeunload事件
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
  if (props.preventBack) {
    // 显示确认对话框
    e.preventDefault();
    e.returnValue = props.confirmMessage;
    return props.confirmMessage;
  }
};

// 添加beforeunload事件监听器
const addBeforeUnloadListener = () => {
  if (!hasAddedListener.value && props.preventBack) {
    window.addEventListener('beforeunload', handleBeforeUnload);
    hasAddedListener.value = true;
  }
};

// 移除beforeunload事件监听器
const removeBeforeUnloadListener = () => {
  if (hasAddedListener.value) {
    window.removeEventListener('beforeunload', handleBeforeUnload);
    hasAddedListener.value = false;
  }
};

// 点击返回按钮
const handleClickBack = () => {
  if (props.preventBack) {
    // 如果启用了防御上一页，显示确认对话框
    if (window.confirm(props.confirmMessage)) {
      // 用户确认离开，移除事件监听器并触发back事件
      removeBeforeUnloadListener();
      emits("back");
      
      // 返回上一页
      router.back();
    }
  } else {
    // 直接触发back事件
    emits("back");
    
    // 返回上一页
    router.back();
  }
};

// 组件挂载时添加事件监听器
onMounted(() => {
  addBeforeUnloadListener();
});

// 组件卸载时移除事件监听器
onUnmounted(() => {
  removeBeforeUnloadListener();
});

// 暴露方法给父组件
defineExpose({
  addBeforeUnloadListener,
  removeBeforeUnloadListener
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
